<!-- 表格组件 -->
<script setup>
import { reactive, watch, defineEmits } from 'vue'
import { storeToRefs } from 'pinia';
import { useDMStore } from '@/store/super-manger/dormitoryMangerStore'
import { submitFormApi } from '@/service/dormitory-manger'

const dmStore = useDMStore();
const { dmInfo } = storeToRefs(dmStore);

const ruleForm = reactive({
    id: '',
    name: '',
    gender: '男',
    phone_number: '',
    username: '',
    password: '',
    building: ''
})

watch(dmInfo, (newValue) => {
    if (newValue.id) {
        const keys = Object.keys(ruleForm);
        for (let key of keys) {
            ruleForm[key] = newValue[key]
        }
    }
})

// 清空表单数据
const clearForm = () => {
    const keys = Object.keys(ruleForm);
    for (let key of keys) {
        ruleForm[key] = '';
    }
}   

// 提交表单数据
const emit = defineEmits(['submit-form']);

const submitForm = async() => {
    const res = await submitFormApi(ruleForm);
    if (res.data.code === 1) {   // 表示修改成功
        emit('submit-form');
    }
}

defineExpose({
    clearForm,
    submitForm
})
</script>

<template>
  <div class="el_form">
    <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="80px"
    >
        <el-form-item label="姓名：" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入姓名"/>
        </el-form-item>
        <el-form-item label="性别：">
            <el-radio-group v-model="ruleForm.gender">
                <el-radio label="男" />
                <el-radio label="女" />
            </el-radio-group>
        </el-form-item>
        <el-form-item label="手机号：" prop="phone_number">
            <el-input v-model="ruleForm.phone_number" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="账号：" prop="username">
            <el-input v-model="ruleForm.username" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item label="密码：" prop="password">
            <el-input 
                v-model="ruleForm.password" 
                type="password" 
                show-password
                placeholder="6位以上且必须含有数字、字母"
            />
        </el-form-item>
        <el-form-item label="宿舍楼：" prop="building">
            <el-input v-model="ruleForm.building" disabled />
        </el-form-item>
    </el-form>
  </div>
</template>

<style scoped lang="less">
.el-form {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-between;
    .el-form-item {
        width: 300px;
    }
}
</style>